var stats_goodsStatus ;
var parcelorderCtrl  = new XFApp.client();
$.views.converters({
	subString : function(val){
		return parcelorderCtrl.subString(val,7);
	},

    formatDate : function(val){
    	var date = new Date(val);
    	return date.format("yyyy-MM-dd hh:mm:ss");
    },
    
    getCurrencys : function(){
    	
    	return dictCtrl.dictionary.translate("currency");
    	
    },
    
	
	formatCurrency : function(val){			
		
		if(!val){
			return "";
		}
		
		var result = "未知类型("+val+")" ;
		for(var index in currencys){
			var dict = currencys[index];
			if(dict.dictCode == val){
				result = dict.dictName;
				break;
			}
		}
		return result;
	},
	
	ftime : function(val){
		if(!!val){
			return val.year+"-"+val.monthValue+"-"+val.dayOfMonth+" "+val.hour+":"+val.minute+":"+val.second;
		}
		return "";
	},

	fgoodsStatus : function(value) {
		if(!value){
			return "";
		}
		for(index in stats_goodsStatus){
			var goodsStatus = stats_goodsStatus[index];
			if(goodsStatus.dictCode == value){
				return goodsStatus.dictName;
			}
		}
		return  "未知类型("+value+")";
	},
	
});
XFApp.client.prototype.parcelorder = {
	parcelOrderPage : null,
	smallPage:null,
	successCode : 10000,
	detailId:null,
	selPage:null,
	goodsResult:null,
	weight:null,
	urlItems : {
		queryListURL : basePath+"/userCenter/parcelorder/queryList",
		removeOrderURL  : basePath+"/userCenter/parcelorder/removeOrder",
		queryLstURL : basePath+"/userCenter/parcelorder/queryLst",
		updateQltURL : basePath+"/userCenter/parcelorder/updateQty",
		updatePriceURL : basePath+"/userCenter/parcelorder/updatePrice",
		updateWeightURL : basePath+"/userCenter/parcelorder/updateWeight",
		delOrOpenURL : basePath+"/userCenter/parcelorder/delOrOpen",
		submitURL : basePath+"/userCenter/parcelorder/submit",
		queryPageURL : basePath+"/nt/parcelOrder/querySKU",
		updateSKUByIdURL:basePath+"/userCenter/parcelorder/updateSKUById",
		queryGoodsURL:basePath+"/userCenter/goodRecord/queryPage",
		copyGoodsURL:basePath+"/userCenter/parcelorder/saveOrderDetail",
		importDataURL:basePath+"/nt/parcelOrder/importData",
		downLoadURL:basePath+"/userCenter/fileDownload/downloadTemplate",
		importBigPkgDataURL:basePath+"/nt/parcelOrder/importBigPkgData", 
		newImportBigPkgDataURL:basePath+"/nt/importExcelTrans/importExcelData",   //sdf重构导入url
		downLoadURLWithRealPath:basePath+"/nt/newIm/downloadTemplate",//下载模板 @ps
		exportErrorGoodsExcel : basePath+"/nt/newIm/exportErrorGoodsExcel",  //下载未成功备案的商品数据
		calWeightURL : basePath+"/userCenter/parcelorder/calWeight",
		updateGoodsURL : basePath+"/nt/parcelOrder/updateGoods",
		removeSKUURL: basePath+"/userCenter/parcelorder/removeSKU",
		findGoodsURL: basePath+"/userCenter/parcelorder/findUniqueGoods",
		findDetailURL: basePath+"/userCenter/parcelorder/findUniqueDetail",
		updateQualityURL : basePath+"/nt/parcelOrder/sync2Quality",
		updateQlt2NumURL : basePath+"/nt/parcelOrder/updateQlt2Num",
		batchSubmitURL : basePath+"/userCenter/parcelorder/batchSubmit",
		queryProgressURL: basePath+"/userCenter/parcelorder/getProcessByKey"
	},
	

	//清空，界面  “移除”  按钮的点击事件sdsds 
	cleanAll : function(idx){
		_this = this;
		var elems = [];
		$("input[name='sku']").each(function(){
			if(!!$(this).attr("name")){
				var param = {name:'',value:''};				
				param.name=$(this).attr("name");
				param.value= $(this).val("");
				elems.push(param);
			}
		});
		var params = {
			detailId : idx,
		};
		
		$.ajax({
			url :_this.urlItems.removeSKUURL,
			data : params,
			dataType : "json",
			type : 'post',
			success : function(data) {
				if(data.isSuccess){
					// window.webDialogUtil.alert("提示",data.msg);	       		 
					$("#sku"+idx).val("");			
					$("#itemname"+idx).text("");
					if(!!$("#awbNo").val()){
						$("#po_search").click();
					}
				}else{
					window.webDialogUtil.alert("提示",data.msg);	  
				}
			}
		});		
	},
	
	skuSelector :function(idx){
		_this = this;	
		_this.detailId = idx;
		_this.selSkuPage();	
		$("#choose_sku_modal").modal();	
	},	
	
	formValidate : function(){
		$("#importForm").validate({
			rules: {
				excelFile : "required"
			},
			messages: {
				excelFile: "请上传数据文件"
			}
		});
		$("#importForm").validate();
	},
	
	formValidate2 : function(){
		$("#importForm2").validate({
			rules: {
				excelBigPkgFile : "required"
			},
			messages: {
				excelBigPkgFile: "请上传数据文件"
			}
		});
		$("#importForm2").validate();
	},
	
	
	findDetail:function(detailId){
		
		_this = this;	
		
		if(!detailId){
			window.webDialogUtil.alert("提示","请选择商品");	     
		}
		
		params = {
			id:detailId
		}
		
		var result = null ;
		
		$.ajax({
			url :_this.urlItems.findDetailURL,
			data : params,
			dataType : "json",
			type : 'post',
			async:false,
			success : function(data) {
				if(data.isSuccess){
					result = data.result ;
				}
			}
		});
		return result ;
	} , 
	
	
	findGoods:function(detailId){
		
		_this = this;	
		
		if(!detailId){
			window.webDialogUtil.alert("提示","请选择商品");	     
		}
		
		params = {
			detailId:detailId
		}
		
		var result = null ;
		
		$.ajax({
			url :_this.urlItems.findGoodsURL,
			data : params,
			dataType : "json",
			type : 'post',
			async:false,
			success : function(data) {
				if(data.isSuccess){
					result = data.result ;
				}
			}
		});
		return result ;
	} ,
	
	
	showSKU:function(sku,detailId){
		
		if(!sku){
			window.webDialogUtil.alert("提示","请先选择SKU，再进行查看");	
			return;
		}
		
		_this.detailId = detailId;
		
		var orderDetail = parcelorderCtrl.parcelorder.findDetail(detailId);
		var goods = parcelorderCtrl.parcelorder.findGoods(detailId);
		
		parcelorderCtrl.parcelorder.openData(orderDetail,goods,detailId);
		
	},
	
	selSkuPage :function(){ 
		_this = this;	
		
		_this.goodsResult = null;
		
		var params = {
			shelfgoodsname : $("#shelfgoodsname").val(),
			shopinternalid : $("#shopinternalid").val()
		}
		
		if(!!_this.selPage){
			_this.selPage.page("remote",0,params);
		}else{
			_this.selPage = $("#page").page({
				pageSize : 10,
				remote: {
					url: _this.urlItems.queryGoodsURL,
			        params: params,
			        success: function (data, pageIndex) {
			        	if(data.code==_this.successCode){
			        		var pageResult = data.result;	
			        		_this.goodsResult = pageResult.itemList ;			        		
			        		$("#data_grid").html($("#dataTmp1").render(_this.goodsResult));
			        	}else{
			        		window.webDialogUtil.alert("提示","数据查询失败!");			        		 
			        	}
			        },error: function (data){			        	
			        	window.webDialogUtil.alert("提示","数据查询失败!");			        	
			        	return;
			        }
				},
				firstBtnText : '首页',
				lastBtnText : '尾页',
				prevBtnText : '上一页',
				nextBtnText : '下一页',
				showInfo : true,
				showJump : true,
				jumpBtnText : '跳转',
				showPageSizes : true,
				infoFormat : '共{pageCount}页'
			});	
		}
	},
	
	//更新货值	
	updatePrice :function(idx,newPrice,oldPrice){
		_this = this;	
		params = {
				orderDetailId : idx ,
				price : newPrice			
		}	
		
		//只读状态不调用后台更新
		if($("#price"+idx).attr("readonly") == "readonly"){
			return ;
		}
		
		$.ajax({
			url :_this.urlItems.updatePriceURL,
			data : params,
			dataType : "json",
			type : 'post',
			success : function(data) {
				if(data.code!= _this.successCode){
					window.webDialogUtil.alert("提示",data.msg);	       		 
					$("#price"+idx).val(oldPrice);
				}
			}
		});
	},

	//更新数量
	updateQlt :function(idx,newQty,oldQty){
		_this = this;	
		params = {
				orderDetailId : idx ,
				qty : newQty			
		}	
		
		//只读状态不调用后台更新
		if($("#qlt"+idx).attr("readonly") == "readonly"){
			return ;
		}
		
		$.ajax({
			url :_this.urlItems.updateQltURL,
			data : params,
			dataType : "json",
			type : 'post',
			success : function(data) {
				if(!data.isSuccess){
					window.webDialogUtil.alert("提示",data.msg);	       		 
					$("#qlt"+idx).val(oldQty);
				}
			}
		});
	},

	//更新商品重量	
	updateWeight :function(idx,newWeight){
		_this = this;	
		params = {
				orderDetailId : idx ,
				weight : newWeight			
		}	
		
		//只读状态不调用后台更新
		if($("#goodsWeight"+idx).attr("readonly") == "readonly"){
			return ;
		}
		
		$.ajax({
			url :_this.urlItems.updateWeightURL,
			data : params,
			dataType : "json",
			type : 'post',
			success : function(data) {
				if(!data.isSuccess){
					window.webDialogUtil.alert("提示",data.msg);	  
					var oldWeight = $("#goodsWeight"+idx).val();
					$("#goodsWeight"+idx).val(oldWeight);
				}
			}
		});
	},	

	//删除/恢复
	delOrOpen:function(idx){
		_this = this;	
		
		var type = $("#delOrOpen").text();
		
		webAlert({
            title:'提示',
            content:'确认执行'+type+'操作吗?',
            opacity:.5,
            bg:"gray",
            width:300,
            height:10,
            button:[
                    {
                    name:"确定",
                    callback:function(){
                    	_this.delConfirm(idx);
                    	this.close();
                    }
                    },{
                    name:"取消",
                    callback:function(){
                  	  this.close();
                    }
                    }]
         });
	},
	
	delConfirm : function (idx){	
		params = {
				orderDetailId : idx 
		}		
		
		$.ajax({
			url :_this.urlItems.delOrOpenURL,
			data : params,
			dataType : "json",
			type : 'post',
			success : function(data) {
				 if(data.code == 10001){	        		  
					 window.webDialogUtil.toast({
						type: 'success',
						title: '删除成功'
					});
					 $("#po_search").click();
	        	 }else{
	        	 	window.webDialogUtil.alert("提示",data.msg);
	        	 }
				 
			},error : function(data) {
				window.webDialogUtil.alert("提示",'数据删除失败!!');
			}
		});
	},
	

	//刷新列表
	refreshList:function(pkgType){
		_this = this;	
		
		if(pkgType == 1)
			_this.loadSmall();
		else
			_this.load();
		
//		var awbNo = $("#awbNo").val() ;
//		console.log("awbNo:"+awbNo);
//		window.location = basePath + "/nt/parcelOrder/index" ;	
//		if(!!awbNo){
//			$("#po_search").click();
//		}
	},
	

	//提交订单
	submitBak :function(pkgType){
		_this = this;	
		$("#pkgType").val(pkgType);
		
		var transNo = $("#transNo").text();
		var orderNo = $("#orderNo").text();
		
		if(!!transNo || !!orderNo){
			window.webDialogUtil.alert("提示","不允许重复提交");
			return ;
		}
		
		params = {
			awbNo : $("#awbNo").val(),
			pkgType:pkgType
		}
		var skuList = {};
		var flag = false;
		
		$("#page_grid input[id^=qlt]").each(function(){
			if(!$(this).val()){
				window.webDialogUtil.alert("提示","商品数量不能为空");
				flag = true;
				return false;
			}
		});
		
		$("#page_grid input[id^=price]").each(function(){
			if(!$(this).val()){
				window.webDialogUtil.alert("提示","商品贷值不能为空");
				flag = true;
				return false;
			}
		});
		
		$("#page_grid input[id^=goodsWeight]").each(function(){
			if(!$(this).val()){
				window.webDialogUtil.alert("提示","商品重量不能为空");
				flag = true;
				return false;
			}
		});
		
		
		$("#page_grid input[id^=sku]").each(function(){
			if(!$(this).val()){
				window.webDialogUtil.alert("提示","请选择商品sku");
				flag = true;
				return false;
			}else{
				if(!skuList[$(this).val()]){
					skuList[$(this).val()]=$(this).attr("id");
				}else{
					window.webDialogUtil.alert("提示","商品sku重复！");
					flag = true;
					return false;
				}
			}
		});
		if(flag){
			return;
		}
		//  $('#searchForm').serialize()
		$.ajax({
			url :_this.urlItems.submitURL,
			data :$('#searchForm').serialize(),
			dataType : "json",
			type : 'post',
			success : function(data) {
				 if(!data.isSuccess){
					 window.webDialogUtil.alert("提示",data.msg);
					 if(!!$("#awbNo").val()){
						$("#po_search").click();
					 }
	         	 }else{ 
	         		 window.webDialogUtil.alert("提示","[运单编号:"+data.result.transNo+",订单编号:"+data.result.orderNo+"]已提交成功...");
	         		 $("#transNo").html(data.result.transNo);
	         		 $("#orderNo").html(data.result.orderNo);
	         		 //禁用所有操作功能
	      		     parcelorderCtrl.parcelorder.disableAll();	
	      		     //局部刷新
	      		     parcelorderCtrl.parcelorder.load();
	      		     parcelorderCtrl.parcelorder.loadSmall();
	      		     
	      		     parcelorderCtrl.parcelorder.showPreAfter(data.result,0);	 
	      		     //默认向后查找
	      		     parcelorderCtrl.parcelorder.preAfter(data.result.afterOrderAwbNo,0);
	         	 }
			},
			error : function() {
				window.webDialogUtil.alert("提示","系统异常");
		    } 
		});
	},


	//提交产品备案
	bak : function(idx){	
		
		var skuCode = $("#sku"+idx).val() ;
		var awbNo =  $("#awbNo").val();
		var chineseName = $("#chineseName"+idx).text();
		var englishName = $("#englishName"+idx).text();
		var curtype = $("#curtype"+idx).text();
		var declaredValue = $("#declaredValue"+idx).text();
		var weight = $("#weight").text();
		var itemName = $("#itemname"+idx).text();
		var quantity = $("#qlt"+idx).val();
		var url ;
		url = basePath+"/userCenter/goodRecord/skuIndex?id="+idx;
		/*if(skuCode !=''){
			if(!!itemName){
				url = basePath+"/userCenter/packageForstats/goodsRecord/skuIndex?itemNo="+skuCode+"&awbNo="+awbNo;
			}else{
				url = basePath+"/nt/packageForstats/goodsRecord/skuCopyIndex?id="+idx+"&itemNo="+skuCode+"&awbNo="+awbNo;
			}
		}else{
			url = basePath+"/nt/packageForstats/goodsRecord/statsIndex?id="+idx+"&declaredValue="+declaredValue+"&quantity="+quantity+"&curtype="+curtype+"&chineseName="+chineseName+"&englishName="+englishName+"&weight="+weight+"&awbNo="+awbNo;
		}*/
		
		window.location.href = url ;	
	},

	//提交产品备案
	bakOfCopy : function(idx){	
		
		var skuCode = $("#sku"+idx).val() ;
		var awbNo =  $("#awbNo").val();
		var chineseName = $("#chineseName"+idx).text();
		var englishName = $("#englishName"+idx).text();
		var curtype = $("#curtype"+idx).text();
		var declaredValue = $("#declaredValue"+idx).text();
		var weight = $("#weight").text();
		var itemName = $("#itemname"+idx).text();
		var url ;
		
		if(skuCode !=''){
			if(!!itemName){
				url = basePath+"/nt/packageForstats/goodsRecord/skuIndex?itemNo="+skuCode+"&awbNo="+awbNo;
			}else{
				url = basePath+"/nt/packageForstats/goodsRecord/skuCopyIndex?id="+idx+"&itemNo="+skuCode+"&awbNo="+awbNo;
			}
		}else{
			url = basePath+"/nt/packageForstats/goodsRecord/statsIndex?id="+idx+"&declaredValue="+declaredValue+"&curtype="+curtype+"&chineseName="+chineseName+"&englishName="+englishName+"&weight="+weight+"&awbNo="+awbNo;
		}
		
		window.location.href = url ;	
	},
	//复制商品
	copy:function(idx){
		var params = {detailId:idx};
		$.ajax({
			url :_this.urlItems.copyGoodsURL,
			data : params,
			dataType : "json",
			type : 'post',
			success : function(data) {
				if(data.code ==_this.successCode){
					var newId = data.result;
					var newCol = $("#col_"+idx).clone();
					var newEleId = newCol.attr("id").replace(idx,newId);
					newCol.attr("id",newEleId);
					newCol.find("[replace-id=true]").each(function(){
						var newEleId = $(this).attr("id").replace(idx,newId);
						$(this).attr("id",newEleId);
						if(!!$(this).attr("data")){
							var newData = $(this).attr("data").replace(idx,newId);
							$(this).attr("data",newData);
						}
					});
					newCol.find("[name='sku_choose']").attr("onclick","javascript:parcelorderCtrl.parcelorder.skuSelector("+newId+");");
					newCol.find("[name='sku_remove']").attr("onclick","javascript:parcelorderCtrl.parcelorder.cleanAll("+newId+");");
				
					var qltAtt = newCol.find("[name='qlt']").attr("onblur");
					newCol.find("[name='qlt']").attr("onblur",qltAtt.replace("updateQlt\("+idx,"updateQlt("+newId));
					
					var priceAtt = newCol.find("[name='price']").attr("onblur");
					newCol.find("[name='price']").attr("onblur",priceAtt.replace("updatePrice\("+idx,"updatePrice("+newId));
					
					var weightAtt = newCol.find("[name='goodsWeight']").attr("onblur");
					newCol.find("[name='goodsWeight']").attr("onblur",weightAtt.replace("updateWeight\("+idx,"updateWeight("+newId));
					
					
					newCol.find("[name='delOrOpen']").attr("onclick","javascript:parcelorderCtrl.parcelorder.delOrOpen("+newId+");").html("删除");
					newCol.find("[name='bak']").attr("onclick","javascript:parcelorderCtrl.parcelorder.bakOfCopy("+newId+");");
					newCol.find("[name='copy']").attr("onclick","javascript:parcelorderCtrl.parcelorder.copy("+newId+");");
					$("#page_grid").append(newCol);
					//$("#itemname"+newId).text("");
					parcelorderCtrl.parcelorder.copyToClipboard();
	        	}else{
	        		window.webDialogUtil.alert("提示",data.msg);
	        	}
			}
		});
	},
	
	
	enableAll: function (){
		
		// $("#submit").attr("href","#");
		//设置disabled属性
		$("#submit").attr("disabled", false);
		 
		$("button[name='delOrOpen']").attr({"disabled":false});
		$("button[name='bak']").attr({"disabled":false});
		$("button[name='sku_choose']").attr({"disabled":false});
		$("button[name='sku_remove']").attr({"disabled":false});
		$("button[name='copy']").attr({"disabled":false});     
		$("input[name='sku']").attr({"readonly":false});       		     
		$("input[name='qlt']").attr({"readonly":false});
		$("input[name='price']").attr({"readonly":false});
		$("input[name='goodsWeight']").attr({"readonly":false});
	},
	

	disableAll:function(){
		 // $("#submit").attr("href","#");
		 //设置disabled属性
		 $("#submit").attr("disabled", true);
		 
		 $("button[name='delOrOpen']").attr({"disabled":true});
		 $("button[name='bak']").attr({"disabled":true});
		 $("button[name='sku_choose']").attr({"disabled":true});
		 $("button[name='sku_remove']").attr({"disabled":true});
		 $("button[name='copy']").attr({"disabled":true});     
		 $("input[name='sku']").attr({"readonly":true});       		     
		 $("input[name='qlt']").attr({"readonly":true});
		 $("input[name='price']").attr({"readonly":true});
		 $("input[name='goodsWeight']").attr({"readonly":true});
	},
	
	selOrder: function (val){
		_this = this;
		//选择之前，先清理掉所有input[name='sku']的值，修复http://pms.crton.com/index.php?m=bug&f=view&bugID=113这个bug
		//TODO 这里有一点点问题，ID是否需要一并清理？ 另外选择器还有一点问题，有另外一个隐藏域是 name='sku'，也一并清理了。问题不大。
		$("input[name='sku']").val("");
		$("#awbNo").val(val);
	    $("#po_search").click();
	    //_this.enableAll();

	},
	
	remove : function (val){
		_this = this;	
		var type = $("#remove").text();
		webAlert({
             title:'提示',
             content:'确认执行'+type+'操作吗?',
             opacity:.5,
             bg:"gray",
             width:300,
             height:10,
             button:[
                     {
                     name:"确定",
                     callback:function(){
                     	_this.removeConfirm(val);
                     	this.close();
                     }
                     },{
                     name:"取消",
                     callback:function(){
                   	  this.close();
                     }
                     }]
          });
	},
	////记录当前页数据，再删除一条数据后局部刷新页面
	curParcelorderItemList: null,
	//数据删除成功后遍历当前页面的数据，将删除成功的数据从数组中去除，然后重新渲染页面	
	delParcelorderForPage: function(id){
		for(var i = 0;i < this.curParcelorderItemList.length;i ++){
			if(this.curParcelorderItemList[i].id == id){
				this.curParcelorderItemList.splice(i,1);
			}
		}
		$("#page_grid2").html($("#pageTmp2").render(this.curParcelorderItemList));
	},
	removeConfirm : function (val){
		val = val + '';
		_this = this;
		var params = {
			ids : val
		};
			
		$.ajax({
			url :_this.urlItems.removeOrderURL,
			data : params,
			dataType : "json",
			type : 'post',
			success : function(data) {
				if(data.code ==_this.successCode){
					if(val.indexOf(',')>=0){
						parcelorderCtrl.parcelorder.load();
                        parcelorderCtrl.parcelorder.loadSmall();
                        $("#awbNo").val("");
                        $("#hideDiv").attr({"style":"display:none;"});
                        _this.loadingDialog.close();
					}else{
						_this.delParcelorderForPage(val);
						parcelorderCtrl.parcelorder.loadSmall();
						$("#awbNo").val("");
                        $("#hideDiv").attr({"style":"display:none;"});
					}
					
					window.webDialogUtil.toast({
						type: 'success',
						title: '操作成功'
					});
					/*webAlert({
			             title:'提示',
			             content: data.msg ,
			             opacity:.5,
			             bg:"gray",
			             width:300,
			             height:10,
			             button:[{
			                     name:"确定",
			                     callback:function(){
			                        parcelorderCtrl.parcelorder.load();
			                        parcelorderCtrl.parcelorder.loadSmall();
			                        $("#awbNo").val("");
			                        $("#hideDiv").attr({"style":"display:none;"});
			                     	this.close();
			                     }
			                     }]
			        });*/
		        }else{
		        	window.webDialogUtil.toast({
						text: data.msg,
						title: '温馨提示'
					});
		        	//window.webDialogUtil.alert("提示",data.msg);
		        }
			}
		});
	},
	
	checkSKU:function(val){
		var check = true;		
		var params = [];
		$("input[name='sku']").each(function(){
			if(!!$(this).attr("name")){
				var param = {name:'',value:''};				
				param.name=$(this).attr("name");
				param.value= $(this).val();
				params.push(param);
			}
		});		
		
		for(var index in params){
			if(val == params[index].value){
				window.webDialogUtil.alert("提示",'该SKU已使用,请选择其它的SKU');
				check = false;
				break;
			}
		}		
		
		return check;
	},
	
	
	selSkuCode :function (val){
		var _this = this;	
		var goods;
		
		var check = parcelorderCtrl.parcelorder.checkSKU(val);
		
		if(check){
			
			for(var index = 0;index<_this.goodsResult.length;index++){				
				var tmp = _this.goodsResult[index];			
				if(tmp.shopinternalid == val){
					goods = tmp;
					break;
				}				
			}
			
			$("#choose_sku_modal").modal('hide');
			
			var params = {
				 detailId : _this.detailId,
				 goodsId  : goods.id
			};
			
			$.ajax({
				url :_this.urlItems.updateSKUByIdURL,
				data : params,
				dataType : "json",
				type : 'post',
				success : function(data) {
					if(data.code ==_this.successCode){
		        		$("#sku"+_this.detailId).val(data.result.shopinternalid);
		        		$("#itemname"+_this.detailId).text(data.result.shelfgoodsname);		        		
		        		$("#price"+_this.detailId).val(data.result.pricermb);
		        		parcelorderCtrl.parcelorder.showData(goods,_this.detailId);
		        	}else{
		        		window.webDialogUtil.alert("提示",data.msg);
		        	}
				}
			});
		}
	},	
	
	
	translation : function (val){
		var data = dictCtrl.dictionary.translate('measureUnit');
		if(!val){
			return "";
		}
		var result = "未知类型("+val+")" ;
		for(var index in data){
			var dict = data[index];
			if(dict.dictCode == val){
				result = dict.dictName;
				break;
			}
		}
		return result;
	},
	
	disableDialog:function(){
		 $("button[name='confirmBtn']").attr({"disabled":true});		
		 $("input[name='applyNum']").attr({"readonly":true});       		     
		 $("input[name='legalNum']").attr({"readonly":true});
		 $("input[name='secondNum']").attr({"readonly":true});
	},
	
	enableDialog:function(){
		 $("button[name='confirmBtn']").attr({"disabled":false});		
		 $("input[name='applyNum']").attr({"readonly":false});       		     
		 $("input[name='legalNum']").attr({"readonly":false});
		 $("input[name='secondNum']").attr({"readonly":false});
	},
	
	
	openData : function (orderDetail,goods,detailId){
		_this = this;
		if(goods == null){
			window.webDialogUtil.alert("提示","未找到商品信息");
			return;
		}
		if(!!$("#transNo").text()){
			parcelorderCtrl.parcelorder.disableDialog();		
		}else{
			parcelorderCtrl.parcelorder.enableDialog();
		}		
		$("#sku").val(orderDetail.sku);
		$("#itemname").val(orderDetail.itemName);
		$("#hiddenId").val(goods.id);
		
		_this.weight = goods.prodweight ;
		
		$("#unitHidden").val(goods.unit);
		$("#unit1Hidden").val(goods.statutoryunit);
		$("#unit2Hidden").val(goods.unit2);
		
		$("#unit").val(parcelorderCtrl.parcelorder.translation(goods.unit));
		$("#unit1").val(parcelorderCtrl.parcelorder.translation(goods.statutoryunit));
		$("#unit2").val(parcelorderCtrl.parcelorder.translation(goods.unit2));
		
		//clear cache
		$("#applyNum").val("");
		$("#legalNum").val("");
		$("#secondNum").val("");
		if(goods){
			if(goods.unit == '035'){
				$("#applyNum").val(orderDetail.legalNum);
			}else{
				$("#applyNum").val(orderDetail.quantity);
			}
			if(goods.statutoryunit == '035'){
				$("#legalNum").val(orderDetail.legalNum);
			}else{
				$("#legalNum").val(orderDetail.quantity);
			}
			if(goods.unit2 == '035'){
				$("#secondNum").val(orderDetail.goodsWeight);
			}else if(goods.unit2){
				$("#secondNum").val(orderDetail.secondNum);
			}else if(!goods.unit2){
				$("#secondNum").val('');
			}
		}else{
			$("#applyNum").val(orderDetail.applyNum);
			$("#legalNum").val(orderDetail.legalNum);
			$("#secondNum").val(orderDetail.secondNum);
		}
		

		$("#show_weight_modal").modal();		
	},
	
	
	getDetail:function(detailId,goods){
		params = {
			id:detailId
		} 
		var result = false;
		$.ajax({
			url :_this.urlItems.findDetailURL,
			data : params,
			dataType : "json",
			type : 'post',
			async: false,
			success : function(data) {				
				if(data.code==_this.successCode){	
					//$("#"+inputId).val(data.result.goodsWeight);
					if(goods){
						if(goods.unit == '035'){
							$("#applyNum").val(data.result.legalNum);
						}else{
							$("#applyNum").val(data.result.quantity);
						}
						if(goods.statutoryunit == '035'){
							$("#legalNum").val(data.result.legalNum);
						}else{
							$("#legalNum").val(data.result.quantity);
						}
						if(goods.unit2 == '035'){
							$("#secondNum").val(data.result.goodsWeight);
						}else if(goods.unit2){
							$("#secondNum").val(data.result.secondNum);
						}else if(!goods.unit2){
							$("#secondNum").val('');
						}
					}else{
						$("#legalNum").val(data.result.legalNum);
						$("#secondNum").val(data.result.secondNum);
						$("#applyNum").val(data.result.applyNum);
					}
					
					$("#goodsWeight"+detailId).val(data.result.goodsWeight);
					result = true ;
	        	}else{	        	
	        		window.webDialogUtil.alert("提示",data.msg);
	        		//$("#"+inputId).val("");
					$("#legalNum").val("");
					$("#secondNum").val("");
					$("#applyNum").val("");
	        		result = false ; 
	        	}
			}
		});
		return result ;
	},
	
	//选择sku商品后，计算单位数量和调整重量。
	showData : function (goods,detailId){
		_this = this;
		parcelorderCtrl.parcelorder.enableDialog();
		
		var qlt = $("#qlt"+detailId).val();
		
		$("#sku").val(goods.shopinternalid);
		$("#itemname").val(goods.shelfgoodsname);		
		$("#hiddenId").val(goods.id);
		_this.weight = goods.netweight ;		
		
		if(!_this.weight){
			window.webDialogUtil.alert("提示","备案商品重量不能为空");
			return;
		}		
		$("#unit1Hidden").val(goods.statutoryunit);		
		$("#unit1").val(parcelorderCtrl.parcelorder.translation(goods.statutoryunit));
		
		$("#unit2Hidden").val(goods.unit2);		
		$("#unit2").val(parcelorderCtrl.parcelorder.translation(goods.unit2));
		
		$("#unitHidden").val(goods.unit);		
		$("#unit").val(parcelorderCtrl.parcelorder.translation(goods.unit));
		
		$("#goodweightHidden").val(goods.netweight);

		var result = false;
		//不知为何此处要增加单位验证，按需求来说任何单位都应该计算重量 pansen
		result = parcelorderCtrl.parcelorder.callData(detailId,goods.netweight,qlt);
		if(result){
			if(!!$("#awbNo").val()){
				$("#po_search").click();
			}
			parcelorderCtrl.parcelorder.getDetail(detailId,goods);
		}
		$("#show_weight_modal").modal();
	},	
	
	updateQlt2Num:function (params){
		_this = this;	
		
		$.ajax({
			url :_this.urlItems.updateQlt2NumURL,
			data : params,
			dataType : "json",
			type : 'post',
			success : function(data) {				
				if(!data.isSuccess){
					window.webDialogUtil.alert("提示",data.msg);
	        	}
			}
		});
	},	
	
	//计算某商品的计量单位的数量，调整所有商品重量
	//prodweight:当前商品单个重量
	//qlt:当前商品数量
	//detailId:运单商品详细编号
	callData:function (detailId,prodweight,qlt){
		_this = this;	
		params = {
			prodweight:prodweight,
			quantity:qlt,
			detailId:detailId
		} 
		var result = false ;
		$.ajax({
			url :_this.urlItems.calWeightURL,
			data : params,
			dataType : "json",
			type : 'post',
			async: false,
			success : function(data) {				
				if(data.code==_this.successCode){
					result = true ;
	        	}else{	        
	        		window.webDialogUtil.alert("提示",data.msg);
	        		result = false;
	        	}
			}
		});
		return result ;
	},
	
	//点击确认按钮的时候，计算重量
	confirmData:function(){
		/*
	    _this = this;	
		var result = false;
		if(!!_this.weight){
			result = parcelorderCtrl.parcelorder.computeWeight(_this.detailId);
		}
		if(result || !!_this.weight){
			$("#show_weight_modal").modal('hide');
		}*/
	},
	
	//这个重量是总重量， == 单个商品重量*数量
	getDetailWeight:function(){
		var proweight;
		if(unit1 == '035'){
			proweight = $("#legalNum").val();
		} else if(unit2 == '035'){	
			proweight = $("#secondNum").val();				
		} else if(unit == '035'){
			proweight = $("#applyNum").val();				
		}
		return proweight;
	},
	
	computeWeight:function (detailId){
		var result = false ;
		var unit1 = $("#unit1Hidden").val();
		var unit2 = $("#unit2Hidden").val();
		var unit = $("#unitHidden").val();
		
		var proweight = $("#goodweightHidden").val();
		//var proweight = parcelorderCtrl.parcelorder.getDetailWeight();
		var qlt = $("#qlt"+detailId).val();

		result = parcelorderCtrl.parcelorder.callData(detailId,proweight,qlt);
		if(result){
			if(!!$("#awbNo").val()){
				$("#po_search").click();
			}
		}
		return result ;
	},
	
	queryByAwbNo:function(pkgType){
		_this = this;	
		params = {
			awbNo : $("#awbNo").val(),
			pkgType:pkgType,
		}
		$.ajax({
			url :_this.urlItems.queryLstURL,
			data : params,
			dataType : "json",
			type : 'post',
			cache:false,
			success : function(data) {				
				if(data.isSuccess){
					
					$("#token").val(data.token);
					
					if(!data.result){
						window.webDialogUtil.alert("提示","运单数据不存在");
						return ;
					}
					
					var dataList = data.result.parcelOrderDetailVoLst;	
					
					if(_this.goodsResult){
						for(var i = 0;i<_this.goodsResult.length;i++){
							for(var k = 0;k<dataList.length;k++){
								if(dataList[k].goodscode == _this.goodsResult[i].docketCode && _this.goodsResult[i].unit == '035'){
									dataList[k].quantity = dataList[k].goodsWeight;
								}
								if(dataList[k].matchSkuUnit == '035'){
									dataList[k].quantity = dataList[k].goodsWeight;
								}
							}
						}
					}else{
						for(var k = 0;k<dataList.length;k++){
							if(dataList[k].matchSkuUnit == '035'){
								dataList[k].quantity = dataList[k].goodsWeight;
							}
						}
					}
					
					
					
					$("#head_grid").html($("#dataTmp2").render(data.result));
					//for(var index = 0;index<_this.goodsResult.length;index++){
	        		$("#page_grid").html($("#dataTmp").render(dataList));
	        		//暂时使用显示选择SKU  然后立马关闭
	        		$("#choose_sku_modal").modal('hide');
	        		// _this.currentGoods = dataList;
	        		// alert(dataList.length);
	        		// var fun = function(){
	        		// 	var dataList = _this.currentGoods;
	        		// 	alert(dataList.length);
	        		// 	for(var i = 0;i<dataList.length;i++){
		        	// 		document.getElementsByName('sku_choose')[i].onclick = parcelorderCtrl.parcelorder.skuSelector;
		        	// 	}	
	        		// }
	        		// window.setTimeout(fun,3000);
	        		
	        		$("#transNo").html(data.result.transNo);
	        		$("#orderNo").html(data.result.orderNo);
	        		
	        		
	        		$("#hideDiv").attr({"style":"display:show;"});
	        		
	        		if(null != dataList && dataList.length > 0){
	        			parcelorderCtrl.parcelorder.copyToClipboard();
	        		}
	        		
	        		//已生在订单信息不能操作
	                if(!!(data.result.transNo)){
	               	 //禁用所有操作功能
	               	  parcelorderCtrl.parcelorder.disableAll();
	                }	
	                	                
	                parcelorderCtrl.parcelorder.showPreAfter(data.result,pkgType);
	                
	        		if(data.code==10010){//法检商品或者重点抽查商品
		        		var json = $.parseJSON(data.msg);
		        		var lawReview = "";
		        		var randomReview = "";
		        		if(json.lawReview.length>0){
		        			lawReview = "法检商品:";
		        			for(var i=0;i<json.lawReview.length;i++){
		        				lawReview += json.lawReview[i].gname+'、'
		        			}
		        		}
		        		if(json.randomReview.length>0){
		        			randomReview = "重点抽查对象:";
		        			for(var i=0;i<json.randomReview.length;i++){
		        				randomReview += json.randomReview[i].gname+'、'
		        			}
		        		}
		        		lawReview = lawReview==""?lawReview:lawReview.substring(0,lawReview.length-1);
		        		randomReview = randomReview==""?randomReview:randomReview.substring(0,randomReview.length-1);
		        		lawReview = (lawReview!=""&&randomReview!="")?lawReview+"</br>":lawReview;
						webDialogUtil.simpleAlert(lawReview+randomReview);
	        		}
	        		
	        	}else{
	        		window.webDialogUtil.alert("提示","数据查询失败");
	        	}
			}
		});		
	},
	

	queryByTimeRange:function(pkgType){
		_this = this;	
		if(pkgType == 1){
			parcelorderCtrl.parcelorder.loadSmall();
		}else{
			parcelorderCtrl.parcelorder.load();
		}
	},
	
	
	queryLst : function(pkgType){		
		_this = this;
		var awbNo = $("#awbNo").val();
		if(!!awbNo){			
			$('#i_show').text("");
			$("[name='reqTimeStart']").val("");
			$("[name='reqTimeEnd']").val("");
			$("[name='timeRang']").val("");
			parcelorderCtrl.parcelorder.queryByAwbNo(pkgType);
		}else{
			$("#awbNo").val("");
			$("#hideDiv").attr({"style":"display:none;"});
			parcelorderCtrl.parcelorder.queryByTimeRange(pkgType);
		}
		
	},	
	
	
	showPreAfter:function(data,pkgType){
		_this = this;
		var innerHtml = '';
		
		var preOrderAwbNo = data.preOrderAwbNo;
		var afterOrderAwbNo = data.afterOrderAwbNo;		
		if (!!preOrderAwbNo){
			innerHtml += "<div class='form-group col-lg-1 col-md-1 col-sm-1'>";
			innerHtml += "<a id='pre' href='#' onclick='parcelorderCtrl.parcelorder.preAfter(\""+preOrderAwbNo+"\",\""+pkgType+"\");'  class='btn btn-primary'>";
		    innerHtml += "<i class='fa  fa-arrow-circle-left' title='左三角形'></i> <span >上一条</span> ";
		    innerHtml += "</a>";
		    innerHtml += "</div>";
		}
		
		if(!preOrderAwbNo){
			innerHtml += "<div class='form-group col-lg-1 col-md-1 col-sm-1' >";
			innerHtml += "<span class='btn btn-default'> <i class='fa fa-arrow-circle-left' title='左三角形'></i> <span>上一条</span>";
			innerHtml += "</span>";
			innerHtml += "</div>";
		}
        
		if (!!afterOrderAwbNo){
			innerHtml += "<div class='form-group col-lg-1 col-md-1 col-sm-1' >";
			innerHtml += "<a id='after' href='#' onclick='parcelorderCtrl.parcelorder.preAfter(\""+afterOrderAwbNo+"\",\""+pkgType+"\");'  class='btn btn-primary'>";
			innerHtml += "<span >下一条</span> <i class='fa fa-arrow-circle-right' title='右三角形'></i> ";
			innerHtml += "</a>";
			innerHtml += "</div>";
		}
		if(!afterOrderAwbNo){
			innerHtml += "<div class='form-group col-lg-1 col-md-1 col-sm-1'>";
			innerHtml += "<span class='btn btn-default'>  <span>下一条</span> <i class='fa fa-arrow-circle-right' title='右三角形'></i>";
			innerHtml += "</span>" ;
			innerHtml += "</div>";
		}		
		
		$("#preAfterDiv").html(innerHtml);
		
	},
	
	
	preAfter:function(data,pkgType){
		
		$("#awbNo").val(data);
		
		if(!!$("#awbNo").val()){
			$("#po_search").click();
		}
	},
	
	//复制
	copyToClipboard: function (){		
		  $('.table-link').each(function(i){
			  var id = $(this).attr('data');
              var path = remoteRes+"/js/plugins/zeroclipboard/ZeroClipboard.swf" ;
			  ZeroClipboard.config({swfPath:path});
			  var client = new ZeroClipboard($(this));
			  client.on('copy', function(event) {
		    	  event.clipboardData.setData('text/plain', $("#copyTxt"+id).val());
		      });
			  client.on('aftercopy', function(event) {
				  window.webDialogUtil.alert("提示",'复制成功');
		      });			 
			  client.on('error', function(event) {
				  console.log( 'ZeroClipboard error of type "' + event.name + '": ' + event.message );
			      ZeroClipboard.destroy();
			  });
		  });
	},
	
	importData:function (){		
		var _this = this;
		var params = [];
		$("input").each(function(){
			if(!!$(this).val() && !!$(this).attr("id")){
				var param = {name:'',value:''};
				param.name=$(this).attr("id");
				param.value=$(this).val();
				params.push(param);
			}
		});
		webDialogUtil.simpleConfrimAlert("是否确认提交", function(){
			//基于ajaxfileUpload.js实现
			$.ajaxFileUpload({
				url : _this.urlItems.importDataURL,
				secureuri : false,
				fileElementId : 'excelFile',//file标签的id
				dataType : 'json',
				data : params,
				success: function (data, status) {
					if(data.code!=10000){
						webDialogUtil.simpleAlert(data.msg, "温馨提示", null, 300, 10);
					}else{
						webDialogUtil.simpleAlert(data.msg, "温馨提示", null, 300, 10);
						parcelorderCtrl.parcelorder.loadSmall();
					}
				},
				error: function (data, status, e) {
					webDialogUtil.simpleAlert("处理异常", "温馨提示");
				}
			});
		});
		
	},
	//下载未能成功备案的商品@ps
	downLoadErroGoods :function (str) {
		var _this = this;
		var data ={"itemName":str};
		$.ajax({
			type: "POST",
			url: parcelorderCtrl.parcelorder.urlItems.exportErrorGoodsExcel,
			data: data,
			success: function(data){
				if(data.success) {
				$("body").append("<iframe id='downLoadErroGoods' src='" +parcelorderCtrl.parcelorder.urlItems.downLoadURLWithRealPath+'?fileName='+ data.fileName +"' frameborder=0 width=0 height=0 style='display:none'></iframe>");
				}
			}
		});
	},
	
	downloadTemplate: function(fileName){
		
		_this = this;
		
		var url = _this.urlItems.downLoadURL+"?fileName="+fileName;
		
		var iframeId = "big_tmpfile_download_frame" ;
		if(fileName == 'template-small-pkg.xls'){
			iframeId =  "small_tmpfile_download_frame";
		}
			
		$("body").append("<iframe id='"+iframeId+"' src='" + url +"' frameborder=0 width=0 height=0 style='display:none'></iframe>");
	},
	
	//新版本导入 @ps
	NewimportData:function (){
		var _this = this;
		var params = [];
		$("input").each(function(){
			if(!!$(this).val() && !!$(this).attr("id")){
				var param = {name:'',value:''};
				param.name=$(this).attr("id");
				param.value=$(this).val();
				params.push(param);
			}
		});
		webDialogUtil.simpleConfrimAlert("是否确认提交", function(){
			//基于ajaxfileUpload.js实现
			_this.loadingDialog = webDialogUtil.loading('正在导入，请稍后...');
			$.ajaxFileUpload({
				url : _this.urlItems.newImportBigPkgDataURL,
				secureuri : false,
				fileElementId : 'excelFile',//file标签的id
				dataType : 'json',
				data : params,
				success: function (data, status) {
					_this.loadingDialog.close();
					if(data.code=='2'){
						webDialogUtil.simpleConfrimAlert("存在没有智能备案成功的商品信息，请确认", function(){_this.downLoadErroGoods(data.msg);});
					}else{
						webDialogUtil.simpleAlert(data.msg, "温馨提示", null, 300, 10);
						parcelorderCtrl.parcelorder.load();
					}
					parcelorderCtrl.parcelorder.load();
				},
				error: function (data, status, e) {
					_this.loadingDialog.close();
					webDialogUtil.simpleAlert("处理异常", "温馨提示");
				}
			});
		});

	},
	
	
	loadSmall : function (){		
        _this = this;
        var parmas = {				
			transNo: true,
			orderNo: true,
		    pkgType:1,
		    reqTimeStart:$("#reqTimeStart").val(),
		    reqTimeEnd:$("#reqTimeEnd").val(),
		}        
        
		if(!!_this.smallPage){
			
			_this.smallPage.page("remote",0, parmas);
		}else{
			_this.smallPage = $("#page1").page({
			pageSize : 10,
			remote: {
				url: _this.urlItems.queryListURL,
		        params: parmas, 
		        success: function (data, pageIndex) {
		        	if(data.isSuccess){
		        		var pageResult = data.result;
		        		if(null == data 
								|| null == data.result 
									|| null == data.result.itemList
										|| data.result.itemList.length < 1){
		        			$("#page_grid1").html('<tr><td align="center" colspan="11">暂无数据</td></tr>');
		        		}else{
		        			
		        			if(pageResult.itemList.length>0){
			        			for(var index in pageResult.itemList){
			        				var element = pageResult.itemList[index];
			        				element["seqNum"]=parseInt(pageResult.pageSize)*(parseInt(pageResult.pageNo)-1)+parseInt(index)+1;
			        			}
			        			
			        			$("#page_grid1").html($("#pageTmp1").render(pageResult.itemList));
			        		}		        			
		        		}
		        		
		        	}else{
		        		window.webDialogUtil.alert("提示","数据查询失败!");			        		  
		        	}
		        	$("#count1").html(data.result.totalRecord+" 条");
		        },
		        error : function(){
		        	window.webDialogUtil.alert("提示","数据查询失败!");
		        }
			},
			firstBtnText : '首页',
			lastBtnText : '尾页',
			prevBtnText : '上一页',
			nextBtnText : '下一页',
			showInfo : true,
			showJump : true,
			jumpBtnText : '跳转',
			showPageSizes : true,
			infoFormat : '共{pageCount}页,{total}项'
		});	
	   }
		
	},
	
	
	//运单列表
	load : function (){		
        _this = this;
        var parmas = {				
			transNo: true,
			orderNo: true,
		    pkgType:2,
		    reqTimeStart:$("#reqTimeStart").val(),
		    reqTimeEnd:$("#reqTimeEnd").val(),
		}     
        
        
        
		if(!!_this.parcelOrderPage){
			
			_this.parcelOrderPage.page("remote",0, parmas);
		}else{
			_this.parcelOrderPage = $("#page2").page({
			pageSize : 10,
			remote: {
				url: _this.urlItems.queryListURL,
		        params: parmas, 
		        success: function (data, pageIndex) {
		        	if(data.isSuccess){
		        		var pageResult = data.result;
		        		if(null == data 
								|| null == data.result 
									|| null == data.result.itemList
										|| data.result.itemList.length < 1){
		        			$("#page_grid2").html('<tr><td align="center" colspan="11">暂无数据</td></tr>');
		        			_this.curParcelorderItemList = null;
		        			parcelorderCtrl.parcelorder.pageList = [];
		        		}else{
		        			
		        			if(pageResult.itemList.length>0){
			        			for(var index in pageResult.itemList){
			        				var element = pageResult.itemList[index];
			        				element["seqNum"]=parseInt(pageResult.pageSize)*(parseInt(pageResult.pageNo)-1)+parseInt(index)+1;
			        			}
			        			
			        			$("#page_grid2").html($("#pageTmp2").render(pageResult.itemList));
			        			_this.curParcelorderItemList = pageResult.itemList;
			        			parcelorderCtrl.parcelorder.pageList = pageResult.itemList;
			        		}		        			
		        		}
		        		
		        	}else{
		        		window.webDialogUtil.alert("提示","数据查询失败!");			        		  
		        	}
		        	$("#count2").html(data.result.totalRecord+" 条");
		        },
		        error : function(){
		        	window.webDialogUtil.alert("提示","数据查询失败!");
		        }
			},
			firstBtnText : '首页',
			lastBtnText : '尾页',
			prevBtnText : '上一页',
			nextBtnText : '下一页',
			showInfo : true,
			showJump : true,
			jumpBtnText : '跳转',
			pageSizeItems: [10,20,30,40,50,100,200],
			showPageSizes : true,
			infoFormat : '共{pageCount}页,{total}项'
		});	
	   }
		
	},
	
	
	updateQuality:function(inputId){
		_this = this;
		
		var val = $("#"+inputId).val();
		
		if(!val){			
			return ;
		}
		
		if(inputId == 'applyNum'){
			
			if(!!unitHidden){
				if(unitHidden == unit1Hidden){
					$("#legalNum").val(val);
				}
				
				if(unitHidden == unit2Hidden){
					$("#secondNum").val(val);
				}
			}else{
				window.webDialogUtil.alert("提示", "申报计量单位为空，不允许修改申报数量");
				return ;
			}			
		}
		
		if(inputId == 'legalNum'){
			
			if(!!unit1Hidden){
				if(unit1Hidden == unitHidden){
					$("#applyNum").val(val);
				}
				
				if(unit1Hidden == unit2Hidden){
					$("#secondNum").val(val);
				}
			}else{
				window.webDialogUtil.alert("提示", "法定计量单位为空，不允许修改法定数量");
				return ;
			}			
		}
		
		if(inputId == 'secondNum'){
			
			if(!!unit2Hidden){
				if(unit2Hidden == unitHidden){
					$("#applyNum").val(val);
				}
				
				if(unit2Hidden == unit1Hidden){
					$("#legalNum").val(val);
				}
			}else{
				window.webDialogUtil.alert("提示", "第二计量单位为空，不允许修改第二数量");
				return ;
			}			
		}
		
		
		params = {
			orderDetailId : _this.detailId ,
			valueTmp : val,
			inputId:inputId
		}

	   $.ajax({
			url : _this.urlItems.updateQualityURL,
			data : params,
			dataType : "json",
			type : 'post',
			success : function(data) {
				if (data.isSuccess) {
					if(!!$("#awbNo").val()){
						$("#po_search").click();
					}
				}else{
					window.webDialogUtil.alert("提示", data.msg);
				} 
			}
		});		
		
	},
	////记录当前页数据，再删除一条数据后局部刷新页面
	pageList: [],
	selectedAwbNos: [],
	batchSubmit: function(){
		var _this = this;
		var ids = [];
		
		if(_this.selectedAwbNos.length == 0){
			window.webDialogUtil.alert("提示", '请选择对应的记录!');
			return;
		}
		
		webDialogUtil.simpleConfrimAlert('是否确认提交'+_this.selectedAwbNos.length+'条运单？', function(){
		    $('#batchNum').html(_this.selectedAwbNos.length);
			$("#modalBatchSubmitParcel").modal({backdrop: 'static', keyboard: false});
			_this.loop = window.setInterval(_this.queryProgress,1000);
			
			$("#selectedAwbNos").html(_this.selectedAwbNos.length);
			$.ajax({
				type: "POST",
				url: parcelorderCtrl.parcelorder.urlItems.batchSubmitURL,
				dataType : 'json',
				traditional:true,
				data: {awbNos: _this.selectedAwbNos,progressKey: progressKey},
				async:true,
				success: function(msg){

				},
				error : function() {
					
				}	
			});
			_this.selectedAwbNos = [];
		});

	},
	queryProgress: function(){
		var _this = this;
		$.ajax({
			type: "POST",
			url: parcelorderCtrl.parcelorder.urlItems.queryProgressURL,
			dataType : 'json',
			data: {progressKey: progressKey},
			async:true,
			success: function(msg){

				parcelorderCtrl.parcelorder.resetProgressBar(msg);
			},
			error : function() {
				
				//parcelorderCtrl.parcelorder.resetProgressBar();
			}	
		});
	},
	reGetProgressCount: 0,
	resetProgressBar: function(msg){
		if(msg){
			$('#doneCount').html(msg.doneCout);
			$('#faildCount').html(msg.faildCount);
			if(msg.doneCout > 0){
				if((msg.doneCout+msg.faildCount) >= msg.total){
					window.clearInterval(parcelorderCtrl.parcelorder.loop);
					$('.progress .progress-bar').attr('data-transitiongoal',100).progressbar({display_text: 'fill'});
					window.setTimeout(function(){
						$("#modalBatchSubmitParcel").modal('hide');
						$('.progress .progress-bar').attr('data-transitiongoal',0).progressbar({display_text: 'fill'});
						$('#doneCount').html(0);
						$('#faildCount').html(0);
						$("#po_search").click();
					},900);
					
				}else{
					$('#doneCount').html(msg.doneCout);
					$('#faildCount').html(msg.faildCount);
					$('.progress .progress-bar').attr('data-transitiongoal',msg.donePercent).progressbar({display_text: 'fill'});
				}
				
			}
			
		}else{
			parcelorderCtrl.parcelorder.reGetProgressCount ++;
			if(parcelorderCtrl.parcelorder.reGetProgressCount >=9){
				parcelorderCtrl.parcelorder.reGetProgressCount = 0;
				window.clearInterval(parcelorderCtrl.parcelorder.loop);
			}
			window.setTimeout(function(){
						$("#modalBatchSubmitParcel").modal('hide');
						$('.progress .progress-bar').attr('data-transitiongoal',0).progressbar({display_text: 'fill'});
						$('#doneCount').html(0);
						$('#faildCount').html(0);
						$("#po_search").click();
					},900);
		}
	},
	event : function(){
		_this = this;	
		
		var pkgType = 2;
		// var reqTimeStart ;
		// var reqTimeEnd ;		
	
		$("#po_search").on("click",function(){
			parcelorderCtrl.parcelorder.enableAll();
			parcelorderCtrl.parcelorder.queryLst(pkgType);
		});
		
		$("#submit").on("click",function(){
			parcelorderCtrl.parcelorder.submitBak(pkgType);
		});
		
		$("#batchSubmitBtn").on("click",function(){
			parcelorderCtrl.parcelorder.batchSubmit();
		});
		
		$("#xClose").on("click",function(){
			$("#choose_sku_modal").hide();
		});
		$("#btnClose").on("click",function(){
			$("#choose_sku_modal").hide();
		});
		
		//
		$("#xBtn").on("click",function(){
			$("#show_weight_modal").hide();
		});
		
		
		$("#confirmBtn").on("click",function(){
			parcelorderCtrl.parcelorder.confirmData();
		});
		
		
		$("#sku_reset").on("click",function(){
			$("#shopinternalid").val("");
			$("#shelfgoodsname").val("");
		});			
		
		$("#importButton").on("click",function(){
			if($("#importForm").validate().form()){
				parcelorderCtrl.parcelorder.importData();
			}
		});

		$("#downloadButton").on("click", function(){
			parcelorderCtrl.parcelorder.downloadTemplate('transTemplate.xls');
		});
		
		$("#importButton2").on("click",function(){
			if($("#importForm2").validate().form()){
				parcelorderCtrl.parcelorder.NewimportData();
			}
		});

		$("#downloadButton2").on("click", function(){
			parcelorderCtrl.parcelorder.downloadTemplate('transTemplate.xls');
		});
		
		$("#applyNum").on("blur", function(){
			parcelorderCtrl.parcelorder.updateQuality('applyNum');
		});	
		
		$("#legalNum").on("blur", function(){
			parcelorderCtrl.parcelorder.updateQuality('legalNum');
		});
		
		$("#secondNum").on("blur", function(){
			parcelorderCtrl.parcelorder.updateQuality('secondNum');
		});
		
		
		$("#bigPkg").on("click", function(){
			pkgType = 2;
			// reqTimeStart = $("#reqTimeStart").val();
			// reqTimeEnd = $("#reqTimeEnd").val();
			parcelorderCtrl.parcelorder.load();
		});
		
		$("#smallPkg").on("click", function(){
			pkgType = 1;
			// reqTimeStart = $("#reqTimeStart").val();
			// reqTimeEnd = $("#reqTimeEnd").val();
			parcelorderCtrl.parcelorder.loadSmall();
		});
		
		$("#refresh").on("click", function(){
			$("#po_search").click();
			$("#refresh").blur();
		});
		
		//表单验证
		_this.formValidate();
		
		//
		_this.formValidate2();
		


		
	},
	initStatus:function(){
		stats_goodsStatus = dictCtrl.dictionary.translate("goodsDocketStatus");
		$.views.converters({
			fgoodsStatus : function(value) {
				if(!value){
					return "";
				}
				for(index in stats_goodsStatus){
					var goodsStatus = stats_goodsStatus[index];
					if(goodsStatus.dictCode == value){
						return goodsStatus.dictName;
					}
				}
				return  "未知类型("+value+")";
			}
		});
	},
	//选择一条记录
	selectedIds: [],
	loop: {},
	selectOne : function(id){
		this.changeSelAll();
		var _this = this;
		var ids = _this.selectedIds;
		if(_this.selectedAwbNos.length >= _this.maxMelectedAwbNos && $("#"+id).is(':checked')){
			window.webDialogUtil.alert("提示", '最多只能选择'+_this.maxMelectedAwbNos+'记录!');
			return;
		}
		var awbNos = _this.getAwbnoById([id]);
		_this.setSelectedAwbNos(awbNos);
		
	},
	//全选和反选切换
	changeSelAll : function(){
		var flag = false;
		$('input:checkbox[name=parcelorderItem]').each(function(i){
			if(this.checked){
				flag = true;
			} 
		});
		if(flag){
			$('#selectAll').html('反选');
		}else{
			$('#selectAll').html('全选');
		}
		
	},
	//复选框全选
	selectAll: function(){
		var ids = [];
		var _this = this;

		if(_this.selectedAwbNos.length >= _this.maxMelectedAwbNos){
			window.webDialogUtil.alert("提示", '最多只能选择'+_this.maxMelectedAwbNos+'记录!');
			return;
		}
		$('input:checkbox[name=parcelorderItem]').each(function(i){
			if(this.checked){
				this.checked = '';
			}else{
				this.checked = 'checked';
			}
			var awbNos = _this.getAwbnoById([this.id]);
			_this.setSelectedAwbNos(awbNos);
		});
		this.changeSelAll();
		
	},
	//通过id获取awbno
	getAwbnoById: function(ids){
		if(ids.length == 0){
			return [];
		}
		var awbNos = [];
		var pageList = parcelorderCtrl.parcelorder.pageList;
		for (var i = ids.length - 1; i >= 0; i--) {
			for(var k = 0; k < pageList.length ; k ++){
				if(ids[i] == pageList[k].id){
					awbNos.push(pageList[k].awbNo);
				}
			}
		}
		return awbNos;
	},
	//记住已选的数据
	setSelectedAwbNos: function(arr){
		if(arr.length == 0){
			return;
		}

		var _this = this;
		var selected = _this.selectedAwbNos;

		
		for(var j = 0; j < arr.length; j ++){
			var isAdd = true;
			for(var i = 0; i < selected.length; i ++){
				if(selected[i] == arr[j]){
					isAdd = false;
					selected.splice(i,1);
				}
			}
			if(isAdd){
				selected.push(arr[j]);
			}

		}
		$("#selectedAwbNos").html(_this.selectedAwbNos.length);
	},
	batchDel: function(){
		var _this = this;
		var ids = '';
		$('input:checkbox[name=parcelorderItem]').each(function(i){
			if(this.checked){
				ids += this.id + ',';
			}
		});
		if(!ids){
			window.webDialogUtil.alert("提示", '请选择对应的记录!');
			return;
		}
		ids = ids.substring(0,ids.length-1);
		var id = ids.split(',');
		webDialogUtil.simpleConfrimAlert('确认删除这'+id.length+'条记录吗？',function(){
			_this.loadingDialog = webDialogUtil.loading('操作进行中...');
			_this.removeConfirm(ids);
		});
		
	},
	loadingDialog: {},
};

var contrys = dictCtrl.dictionary.translate("nation");
$.views.converters({
	ftime : function(value) {
		return value.substring(0,10) ;
	},
	fcontry : function(value){
		if(!value){
			return "";
		}
		for(index in contrys){
			var contry = contrys[index];
			if(contry.dictCode == value){
				return contry.dictName;
			}
		}
	}

});

$(function(){

	$("#awbNo").keydown(function(event) {
		var key = event.keyCode || event.which;
		if (key == 13 || (key == 10 && $.browser.msie && $.browser.version <= 6.0)) {
			parcelorderCtrl.parcelorder.queryLst(3);
			//$("#po_search").click();
			$("#awbNo").select();
		}
	});

	parcelorderCtrl.parcelorder.event();
	parcelorderCtrl.parcelorder.load();
	parcelorderCtrl.parcelorder.loadSmall();
	parcelorderCtrl.parcelorder.initStatus();
	if(!!$("#awbNo").val()){
		$("#po_search").click();
	}
});
